import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/api/api_service.dart';
import 'package:flutter_base/componet/alert.dart';
import 'package:flutter_base/componet/base_widget.dart';
import 'package:flutter_base/model/article_model.dart';
import 'package:flutter_base/model/banner_data.dart';
import 'package:flutter_base/pull_refresh.dart';
import 'package:flutter_base/select_image.dart';
import 'package:flutter_base/universal.dart';
import 'package:flutter_base/util/string_extension.dart';
import 'package:flutter_base/we_chat_picker.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, this.title}) : super(key: key);
  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController controller = TextEditingController();
  String? title;
  List<BannerBean> bannerDataList = [];
  List<Datas> articleList = [];

  Future retrieveBannerData() async {
    // ApiService().getHomeBanner((BannerData bannerData) {
    //   bannerDataList.addAll(bannerData.bannerBean!);
    //   log('length:${bannerDataList.length}');
    //   setState(() {});
    // });
    ApiService().getHomeArticleList(1,(ArticleModel articleModel) {
      articleList.addAll(articleModel.datas);
      log('articleList title:${articleList[0].title}');
      setState(() {});
    });
  }

  @override
  void initState() {
    super.initState();
    retrieveBannerData();
  }
  @override
  Widget build(BuildContext context) {
    DateTime? _lastPressedTime;
    title = '10';
    //扩展类
    title?.toInt();
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title!),
      ),
      body: Universal(
        color: Colors.white,
        isScroll: true,
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        width: double.infinity,
        onTap: () {},
        opacity: 0.6,
        visible: true,
        children: [
          const Text('你好'),
          ElevatedButton(
            child: const Text('选择图片'),
            onPressed: () =>
                Navigator.push(context, MaterialPageRoute(builder: (context) => SelectImagePage())),
            style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.blue)),
          ),
          const Divider(height: 15),
          // ElevatedButton(
          //   child: const Text('选择图片()'),
          //   onPressed: () => Navigator.push(
          //       context, MaterialPageRoute(builder: (context) => WeChatPickerPage())),
          //   style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.blue)),
          // ),
          if(true)
          const Divider(height: 15),
          ElevatedButton(
            child: const Text('刷新组件'),
            onPressed: () =>
                Navigator.push(context, MaterialPageRoute(builder: (context) => PullRefreshPage())),
            style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.blue)),
          ),
          ElevatedButton(
            child: const Text('输入框'),
            onPressed: () async {
              final data = await showInputDialog(context, controller);
              print('输入的内容：$data');
            },
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(Colors.blue),
              foregroundColor: MaterialStateProperty.all(Colors.red),
            ),
          ),
          CommonButton(
              text: '输入框',
              onTap: () async {
                final data = await showInputDialog(context, controller);
                print(data);
              }),
          // Button(
          //   onPressed: () => Fluttertoast.showToast(msg: '封装按钮及文本Widget'),
          //   backgroundColor: Colors.blue,
          //   elevation: 15,
          //   minimumSize: const Size(60, 80),
          //   child: const DefaultText('封装按钮及文本Widget', fontSize: 15, color: Color(0xffffffff)),
          // ),

          ///全局配置
          RefreshConfiguration(
              headerBuilder: () => const WaterDropHeader(),
              // 配置头部默认下拉刷新视图
              footerBuilder: () => const ClassicFooter(),
              // 配置底部默认上拉加载视图
              headerTriggerDistance: 80.0,
              // 自定义弹回动画
              maxOverScrollExtent: 100,
              //The maximum dragging range of the head. Set this property if a rush out of the view area occurs
              maxUnderScrollExtent: 0,
              // Maximum dragging range at the bottom
              enableScrollWhenRefreshCompleted: true,
              //This property is incompatible with PageView and TabBarView. If you need TabBarView to slide left and right, you need to set it to true.
              enableLoadingWhenFailed: true,
              //In the case of load failure, users can still trigger more loads by gesture pull-up.
              hideFooterWhenNotFull: false,
              // Disable pull-up to load more functionality when Viewport is less than one screen
              enableBallisticLoad: true,
              child: const SizedBox()),
          WillPopScope(
            child: const SizedBox(),
            onWillPop: () async {
              print('WillPopScope================');
              if (_lastPressedTime == null ||
                  DateTime.now().difference(_lastPressedTime!) > const Duration(seconds: 2)) {
                //两次点击间隔超过2秒则重新计时
                _lastPressedTime = DateTime.now();
                // Fluttertoast.showToast(msg: '再次点击退出');
                return false;
              }
              return true;
            },
          )
        ],
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

}

class CommonButton extends StatelessWidget {
  const CommonButton({Key? key, this.text, this.onTap}) : super(key: key);
  final GestureTapCallback? onTap;
  final String? text;

  @override
  Widget build(BuildContext context) {
    ///todo
    return ElevatedButton(
      child: Text(text??''),
      // onPressed: () => onTap.call(),
      onPressed: onTap,
      style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.blue)),
    );
  }
}
